package abq2.jic.jic.plugin.operate.askForLeave;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.form.gpt.IGPTAction;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/*
                              _ooOoo_
                             o8888888o
                             88" . "88
                             (| -_- |)
                             O\  =  /O
                          ____/`---'\____
                        .'  \\|     |//  `.
                       /  \\|||  :  |||//  \
                      /  _||||| -:- |||||-  \
                      |   | \\\  -  /// |   |
                      | \_|  ''\---/''  |   |
                      \  .-\__  `-`  ___/-. /
                    ___`. .'  /--.--\  `. . __
                 ."" '<  `.___\_<|>_/___.'  >'"".
                | | :  `- \`.;`\ _ /`;.`/ - ` : | |
                \  \ `-.   \_ __\ /__ _/   .-` /  /
           ======`-.____`-.___\_____/___.-`____.-'======
                              `=---='
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                      佛祖保佑        永无BUG
             佛曰:
                    写字楼里写字间，写字间里程序员；
                    程序人员写程序，又拿程序换酒钱。
                    酒醒只在网上坐，酒醉还来网下眠；
                    酒醉酒醒日复日，网上网下年复年。
                    但愿老死电脑间，不愿鞠躬老板前；
                    奔驰宝马贵者趣，公交自行程序员。
                    别人笑我忒疯癫，我笑自己命太贱；
                    不见满街漂亮妹，哪个归得程序员？
 */

/**
 * 用于智能简历生成
 */
public class AskForLeave implements IGPTAction {
    @Override
    public Map<String, String> invokeAction(String action, Map<String, String> params) {
        Map<String , String> result = new HashMap<>();
        if ("GET_INFO_JSON".equalsIgnoreCase(action)) {
            //将无效字符进行处理
            String jsonResult = params.get("jsonResult").replaceAll("\\s*|\r|\n|\t","");
            JSONObject resultJsonObject = null;
            try {
                //若全部生成JSON字符串，则不会进入catch
                resultJsonObject = JSON.parseObject(jsonResult);
            } catch (Exception ee) {
                //将"ability"的上一个字符作为开始，以}字符作为结束，则最后需要+1
                jsonResult = jsonResult.substring(jsonResult.indexOf("\"reasonForLeave\"")-1 , jsonResult.indexOf("}")+1);
                resultJsonObject = JSON.parseObject(jsonResult);
            }
            //new一个DynamicObject表单对象
            DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject("abq2_apply");
            StringBuilder sb1 = new StringBuilder(); //生成一个单据编号
            sb1.append("AskForLeave-");
            for (int i = 1; i <= 10; i++) {
                int ascii = 48 + (int) (Math.random() * 9);
                char c = (char) ascii;
                sb1.append(c);
            }
            //设置对应属性
            //将获取到的json信息保存到单据中去
            dynamicObject.set("billno", sb1.toString()); //单据编号
            dynamicObject.set("abq2_creator", RequestContext.get().getCurrUserId()); //创建人
            dynamicObject.set("abq2_billstatus", "A");
            dynamicObject.set("billstatus", "A");
            dynamicObject.set("abq2_largetextfield",resultJsonObject.getString("reasonForLeave")); //请假理由
            try {
                dynamicObject.set("abq2_time_begin",new SimpleDateFormat("yyyy-MM-ddHH:mm:ss").parse(resultJsonObject.getString("timeBegin"))); //请假开始时间
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            try {
                dynamicObject.set("abq2_time_end",new SimpleDateFormat("yyyy-MM-ddHH:mm:ss").parse(resultJsonObject.getString("timeEnd"))); //请假时间结束
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            dynamicObject.set("abq2_combofield",resultJsonObject.getString("leaveType")); //请假类型
            DynamicObject myStuInfo = BusinessDataServiceHelper.loadSingle("abq2_tk_student_info",
                    "creator,abq2_textfield,abq2_textfield8,abq2_textfield5"
                    , new QFilter[]{new QFilter("creator", QCP.equals, RequestContext.get().getCurrUserId())});
            dynamicObject.set("abq2_textfield",myStuInfo.getString("abq2_textfield")); //班级
            dynamicObject.set("abq2_textfield1",myStuInfo.getString("abq2_textfield8")); //学号
            dynamicObject.set("abq2_phone",myStuInfo.getString("abq2_textfield5"));
             //保存数据 生成简历信息
            SaveServiceHelper.saveOperate("abq2_apply", new DynamicObject[] {dynamicObject}, null);
            Long pkId = (Long) dynamicObject.getPkValue();
            //拼接URL字符串
            String targetForm = "bizAction://currentPage?gaiShow=1&selectedProcessNumber=processNumber&gaiAction=showBillForm&gaiParams={\"appId\":\"abq2_jic_s\",\"billFormId\":\"abq2_apply\",\"billPkId\":\""+pkId+"\"}&title=请假信息 &iconType=bill&method=bizAction";
            System.out.println(targetForm);
            result.put("formUrl", targetForm);//生成的表单的地址

            result.put("resultJsonObject", resultJsonObject.toJSONString());
        }
        return result;
    }
}